package com.da.javatest.leetCode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenlida
 * @date 2019/1/14 14:18
 * @description
 */
public class Code36 {
    private List<Character> list = new ArrayList<>();

    public boolean isValidSudoku(char[][] board) {
        return checkColumn(board) && checkRow(board) && checkBlock(board);
    }

    private boolean checkColumn(char[][] board) {
        for (int i = 0; i < board.length; i++) {
            list.clear();
            for (char[] b : board) {
                char val = b[i];
                if (val != '.' && list.contains(val)) {
                    return false;
                }
                list.add(val);
            }
        }
        return true;
    }

    private boolean checkRow(char[][] board) {
        for (char[] b : board) {
            list.clear();
            for (char c : b) {
                if (c != '.' && list.contains(c)) {
                    return false;
                }
                list.add(c);
            }
        }
        return true;
    }

    private boolean checkBlock(char[][] board) {
        List<Character> l1 = new ArrayList<>();
        List<Character> l2 = new ArrayList<>();
        List<Character> l3 = new ArrayList<>();
        for (int i = 0; i < board.length; i++) {
            if (i % 3 == 0) {
                l1.clear();
                l2.clear();
                l3.clear();
            }
            for (int j = 0; j < board.length; j++) {
                int flag = j / 3;
                char val = board[i][j];
                if (val == '.') {
                    continue;
                }
                if (flag == 0) {
                    if (l1.contains(val)) {
                        return false;
                    }
                    l1.add(val);
                }
                if (flag == 1) {
                    if (l2.contains(val)) {
                        return false;
                    }
                    l2.add(val);
                }
                if (flag == 2) {
                    if (l3.contains(val)) {
                        return false;
                    }
                    l3.add(val);
                }
            }
        }
        return true;
    }

}
